package com.snifferx.managedbeans;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import org.apache.commons.collections.list.SetUniqueList;
import org.jboss.logging.Logger;

import com.snifferx.domain.AuthorityEntity;
import com.snifferx.domain.UserEntity;
import com.snifferx.model.TempRoleView;
import com.snifferx.services.RolePermissionService;
import com.snifferx.services.UserService;

@ManagedBean(name = "roleAccessBean")
@SessionScoped
public class RoleAccessBean implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -8143191375816256221L;

	private static Logger log = Logger.getLogger(RoleAccessBean.class);

	Collection<AuthorityEntity> authorities;
	AuthorityEntity authorityEntity;
	@ManagedProperty(value = "#{rolePermissionService}")
	private RolePermissionService rolePermissionService;
	// get loginBean
	@ManagedProperty(value = "#{loginBean}")
	private LoginBean loginBean;
	private List<TempRoleView> tempRoleViews;
	private TempRoleView selectedTempRoleView = new TempRoleView();

	// test roleShow
	// private List<String> selectedRoles = new ArrayList<String>();
	// private Map<String, String> allRoles;
	
	@ManagedProperty(value = "#{userService}")
	//@Autowired (Be used just when become a spring bean)
	private UserService userService;

	public RoleAccessBean() {
		super();
		/*
		 * allRoles = new HashMap<String, String>();
		 * allRoles.put("ADMINISTRATOR", "ROLE_ADMINISTRATOR");
		 * allRoles.put("USER", "ROLE_USER"); allRoles.put("GUEST",
		 * "ROLE_GUEST"); allRoles.put("TEST", "ROLE_TEST");
		 */
	}

	public String getCurrentRole() {
		try {
			log.debug("get current user role...");
			authorityEntity = rolePermissionService.loadAuthorityEntityByUsername(loginBean.getUser().getUsername());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	// @PostConstruct
	public void getRoles() {
		try {
			log.debug("get roles...");
			authorities = rolePermissionService.getAllroles();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@PostConstruct
	public void getRolesView() {
		Collection<Object> values = rolePermissionService.getAllrolesJoinView();

		log.debug("ResultList size is:" + values.size());
		// deal with list, in order to filter
		// convert collection to list
		List list;
		if (values instanceof List)
			list = (List) values;
		else
			list = new ArrayList(values);
		// Collections.sort(list);//排序要实现compareTo接口

		List<UserEntity> userEntitys = SetUniqueList.decorate(new ArrayList<UserEntity>());
		List<AuthorityEntity> authorityEntities = new ArrayList<AuthorityEntity>();
		for (int i = 0; i < values.size(); i++) {
			Object[] objs = (Object[]) list.get(i);
			userEntitys.add((UserEntity) objs[0]);
			authorityEntities.add((AuthorityEntity) objs[1]);
		}
		tempRoleViews = new ArrayList<TempRoleView>();
		// 第一层for循环，遍历一的一方user
		for (int i = 0; i < userEntitys.size(); i++) {
			// 从users中获取user
			UserEntity userEntity = userEntitys.get(i);
			// 将结果集set至TempClass中，然后在页面上显示出来。(在此处封装好可能的role)
			TempRoleView tempRoleView = new TempRoleView(userEntity);
			// 将user存入至tempClass中
			tempRoleView.setUser(userEntity);
			// 用一个list来接收多个与单个user对应的role
			ArrayList<AuthorityEntity> roles = new ArrayList<AuthorityEntity>();
			// 第二层for循环，遍历多的一方roles
			for (int j = 0; j < authorityEntities.size(); j++) {
				// 从roles获取role
				AuthorityEntity role = authorityEntities.get(j);
				// 判断user中的id是否与role中的username相等。通过这样比较才能取出与此user相对应的role。
				if ((role != null) && (userEntity.getUsername().equals(role.getUser().getUsername()))) {
					log.debug("role is " + role.getAuthority());
					roles.add(role);
				}
			}

			tempRoleView.setRoles(roles);
			tempRoleViews.add(tempRoleView);

			log.debug("tempRoleViews size = " + tempRoleViews.size());
			log.debug("role size = " + roles.size());
		}

	}

	public String doUpdate() {
		// update userInfo to DB
		// 1.get the select object(user and role ) --log ouput to check 
		log.debug("-----------------------------------------");
		log.debug("this userName :" + this.selectedTempRoleView.getUser().getUsername());
		for (AuthorityEntity e : this.selectedTempRoleView.getRoles()) {
			log.debug("Select role:" + e.getAuthority());
		}
		//test if set to userEntity
		log.debug("Old roles size() = " + this.selectedTempRoleView.getUser().getAuthorities().size());
		//added the action that deal with new select role here
		//step 1: removed old roles
		this.selectedTempRoleView.getUser().getAuthorities().clear();
		//step 2: added new select roles;
		this.selectedTempRoleView.getUser().getAuthorities().addAll(this.selectedTempRoleView.getRoles());
		log.debug("New roles size() = " + this.selectedTempRoleView.getUser().getAuthorities().size());
		//invoke the service to do update operation 
		boolean result = userService.updateUserEntity(this.selectedTempRoleView.getUser());
		if (!result) {
			//show error info
			//do nothing
		}else{		//if success.load new roles again
			this.getRolesView();
			
		}
		
		
		return null;
	}

	public Collection<AuthorityEntity> getAuthorities() {
		return authorities;
	}

	public void setAuthorities(Collection<AuthorityEntity> authorities) {
		this.authorities = authorities;
	}

	public AuthorityEntity getAuthorityEntity() {
		return authorityEntity;
	}

	public void setAuthorityEntity(AuthorityEntity authorityEntity) {
		this.authorityEntity = authorityEntity;
	}

	public RolePermissionService getRolePermissionService() {
		return rolePermissionService;
	}

	public void setRolePermissionService(RolePermissionService rolePermissionService) {
		this.rolePermissionService = rolePermissionService;
	}

	public LoginBean getLoginBean() {
		return loginBean;
	}

	public void setLoginBean(LoginBean loginBean) {
		this.loginBean = loginBean;
	}

	public List<TempRoleView> getTempRoleViews() {
		return tempRoleViews;
	}

	public void setTempRoleViews(List<TempRoleView> tempRoleViews) {
		this.tempRoleViews = tempRoleViews;
	}

	public TempRoleView getSelectedTempRoleView() {
		return selectedTempRoleView;
	}

	public void setSelectedTempRoleView(TempRoleView selectedTempRoleView) {
		this.selectedTempRoleView = selectedTempRoleView;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	/*
	 * public List<String> getSelectedRoles() { return selectedRoles; }
	 * 
	 * public void setSelectedRoles(List<String> selectedTempRoles) {
	 * this.selectedRoles.clear(); this.selectedRoles = selectedTempRoles;
	 * selectedTempRoles = null; }
	 * 
	 * public Map<String, String> getAllRoles() { return allRoles; }
	 * 
	 * public void setAllRoles(Map<String, String> allRoles) { this.allRoles =
	 * allRoles; }
	 */

}
